package ar.com.ctrln.view.render.mantenimiento.ticket;


import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.zkoss.spring.security.SecurityUtil;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Image;
import org.zkoss.zul.Label;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;

import ar.com.ctrln.persistence.model.sistema.cuentas.Autorizacion;
import ar.com.ctrln.persistence.model.sistema.cuentas.Usuario;
import ar.com.ctrln.persistence.model.ticket.Ticket;

public class TicketRowRender implements RowRenderer<Ticket> {

	@Override
	public void render(Row row, Ticket data,int arg) throws Exception {

		Usuario user;
		user = (Usuario)SecurityUtil.getAuthentication().getPrincipal();
		Set<Autorizacion> autorizaciones = (Set<Autorizacion>) user.getAuthorities();
		boolean isAuthored= false;
		for (Autorizacion auto : autorizaciones){
			if(auto.getAuthority().equals("ROLE_ADMIN"))
				isAuthored=true;
		}
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");

		row.appendChild(new Label(data.getOrganizacion().getRazonSocial()));
    	row.appendChild(new Label(sdf.format(data.getFechaLimite())));
    	row.appendChild(new Label(data.getPrioridad()));
    	row.appendChild(new Label(data.getTipoTicket().getNombre()));
    	EstadosTicket currentDay = EstadosTicket.valueOf(data.getEstado());
		Hbox state = new Hbox();
		Image img4 = new Image();
		Hbox box = new Hbox();
        box.setSpacing("12px");
        box.setWidth("100%");
        box.setPack("center");
        Image img1 = new Image();
        Image img2 = new Image();
        Image img3 = new Image();
		switch (currentDay) {
	        case Cerrado:
	        	img4.setSrc("/resources/icons/bTablaCerrarTicket.png");
	        	img3.setSrc("/resources/icons/newActTablaGray.png");
	        	break;
	        case Pendiente:
	        	img4.setSrc("/resources/icons/bTablaPendienteTicket.png");
	        	img3.setSrc("/resources/icons/newActTablaBlue.png");
	    		img3.addEventListener("onClick", new AgregarActListener());
	            break;
	        case Cancelado:
	        	img4.setSrc("/resources/icons/bTablaCancelarTicket.png");
	        	img3.setSrc("/resources/icons/newActTablaGray.png");
	            break;
	        case Esperando:
	        	img4.setSrc("/resources/icons/bTablaEsperandoTicket.png");
	        	img3.setSrc("/resources/icons/newActTablaGray.png");
	        	break;
	        case Programado:
	        	img4.setSrc("/resources/icons/bTablaEsperandoTicket.png");
	        	img3.setSrc("/resources/icons/newActTablaBlue.png");
	    		img3.addEventListener("onClick", new AgregarActListener());
	        	break;
	    }
					
		img4.setWidth("24px");
		img4.setHeight("24px");
		img4.setParent(state);
		new Label("  "+data.getEstado()).setParent(state);
		state.setAlign("center");
		state.setParent(row);
    	
    	
    	
        img1.setSrc("/resources/icons/verTabla2.png");
        img2.setSrc("/resources/icons/feedbackTabla.png");
     
        img1.setTooltiptext("Ver detalle de Ticket");
        img2.setTooltiptext("Dar por finalizado el reclamo");
        img3.setTooltiptext("Agregar una nueva Actividad");
	    img1.setParent(box);
        
	    if(isAuthored){
	    img3.setParent(box);
	    if(data.getEstado().equals(Ticket.ESTADO_PENDIENTE))
    		Clients.showNotification("Nuevo Ticket de cliente",Clients.NOTIFICATION_TYPE_INFO, row, "end_center", 7000);
	    }
	    else{
	    	if(data.getEstado().equals(Ticket.ESTADO_ENESPERA)){
	    		img2.setParent(box);
	    		Clients.showNotification("Ticket esperando su evaluacion y respuesta",Clients.NOTIFICATION_TYPE_INFO, row, "end_center", 7000);
	
	    	}
	    }
        box.setParent(row);
        row.setTooltiptext(data.getDescripcion());
		row.setAttribute("data", data);
		// Manejo de eventos de cada boton-imagen de de la tabla
		img1.addEventListener("onClick", new VerTicketListener());
		img2.addEventListener("onClick", new CerrarTicketListener());
	}
}

class VerTicketListener implements org.zkoss.zk.ui.event.EventListener {

	@Override
	public void onEvent(Event evt) throws Exception {

		Ticket ticket = (Ticket) ((Row) evt.getTarget().getParent().getParent()).getAttribute("data");
		Map<String, Ticket> args = new HashMap<String, Ticket>();
		args.put("data", ticket);
		Executions.createComponents("/zul/mantenimiento/tickets/verTicket.zul",null
				, args);
	}
}

class AgregarActListener implements org.zkoss.zk.ui.event.EventListener {

	@Override
	public void onEvent(Event evt) throws Exception {

		Ticket ticket = (Ticket) ((Row) evt.getTarget().getParent().getParent()).getAttribute("data");
		Map<String, Ticket> args = new HashMap<String, Ticket>();
		args.put("ticket", ticket);
		Executions.createComponents(
				"/zul/mantenimiento/tickets/nuevaActividad.zul",
				null, args);
	}
}

class CerrarTicketListener implements org.zkoss.zk.ui.event.EventListener {

	@Override
	public void onEvent(Event evt) throws Exception {

		Ticket ticket = (Ticket) ((Row) evt.getTarget().getParent().getParent()).getAttribute("data");
		Map<String, Ticket> args = new HashMap<String, Ticket>();
		args.put("data", ticket);
		Executions.createComponents("/zul/mantenimiento/tickets/cerrarTicket.zul",null
				, args);
	}
}




